package radiostation;

import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.table.DefaultTableModel;
import model.Song;

public final class SelectSongForm extends BaseJFrame {

    private final EntityManager entityManager;
    private final List<Song> playlistSongs;
    private final PlaylistEditUI parent;

    public SelectSongForm(EntityManager em, List<Song> playlistSongs, PlaylistEditUI parent) {
        this.entityManager = em;
        this.playlistSongs = playlistSongs;
        this.parent = parent;
        initComponents();

        setLocationRelativeTo(null);

        bindSongTable();
    }

    public void bindSongTable() {

        DefaultTableModel defaultTableModel = (DefaultTableModel) songTable.getModel();
        defaultTableModel.setRowCount(songList.size());

        for (int i = 0; i < songList.size(); i++) {

            Song s = (Song) songList.get(i);
            String title = s.getTitle();
            String singers = "";
            if (s.getAlbum() != null) {
                if(s.getAlbum().getArtist() != null){
                    singers += s.getAlbum().getArtist().getArtisticName();
                }
                if (singers.length() > 0) {
                    singers += ", ";
                }
                if(s.getAlbum().getMusicGroup()!= null){
                    singers += s.getAlbum().getMusicGroup().getName();
                }
            }

            int duration = s.getDuration();

            defaultTableModel.setValueAt(title, i, 0);
            defaultTableModel.setValueAt(singers, i, 1);
            defaultTableModel.setValueAt(duration, i, 2);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        songQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT s FROM Song s");
        songList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : songQuery.getResultList();
        selectSongLabel = new javax.swing.JLabel();
        songScrollPane = new javax.swing.JScrollPane();
        songTable = new javax.swing.JTable();
        searchTF = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();
        selectSongButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Επιλογή Τραγουδιού");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        selectSongLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        selectSongLabel.setText("Επιλογή Τραγουδιού");

        songTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Τίτλος", "Καλλιτέχνης/Συγκρότημα", "Διάρκεια"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        songTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        songScrollPane.setViewportView(songTable);

        searchTF.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                searchTFKeyTyped(evt);
            }
        });

        searchButton.setText("Αναζήτηση");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        selectSongButton.setText("Επιλογή");
        selectSongButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectSongButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(songScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(177, 177, 177)
                                .addComponent(selectSongLabel))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(searchTF, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(searchButton)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(205, 205, 205)
                .addComponent(selectSongButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(selectSongLabel)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(songScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(selectSongButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed

        String searchCriteria = searchTF.getText().toLowerCase();
        // get all songs
        songList = songQuery.getResultList();
        // if search string not null
        if (!searchCriteria.equals("")) {
            //remove songs from list that are not matched
            for (int i = songList.size() - 1; i >= 0; i--) {
                boolean hasCriteria = false;
                Song s = (Song) songList.get(i);
                
                // title check
                if (s.getTitle().toLowerCase().contains(searchCriteria)) {
                    hasCriteria = true;
                }
                
                // artistic name check
                if (s.getAlbum().getArtist().getArtisticName().toLowerCase().contains(searchCriteria)) {
                    hasCriteria = true;
                }

                // group name check
                if (s.getAlbum().getMusicGroup().getName().toLowerCase().contains(searchCriteria)) {
                    hasCriteria = true;
                }

                //remove from list if not matched
                if (!hasCriteria) {
                    songList.remove(i);
                }
            }
        }
        
        bindSongTable();
    }//GEN-LAST:event_searchButtonActionPerformed

    private void selectSongButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectSongButtonActionPerformed

        // get selected song
        int selectedRow = songTable.getSelectedRow();

        // check if selected song
        if (selectedRow == -1) {
            showWarningMessage("Δεν έχει επιλεχθεί τραγούδι");
            return;
        }

        Song selectedSong = (Song) songList.get(selectedRow);

        // check if song already in list
        if (playlistSongs.contains(selectedSong)) {
            showWarningMessage("Το τραγούδι υπάρχει ήδη στην λίστα");
            return;
        }

        // update list management
        parent.setSelectedSong(selectedSong);

        closeFrame(true);

    }//GEN-LAST:event_selectSongButtonActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        closeFrame(false);
    }//GEN-LAST:event_formWindowClosing

    private void searchTFKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchTFKeyTyped
        // on enter press
        if (evt.getKeyChar() == '\n') {
            searchButtonActionPerformed(null);
        }
    }//GEN-LAST:event_searchTFKeyTyped

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton searchButton;
    private javax.swing.JTextField searchTF;
    private javax.swing.JButton selectSongButton;
    private javax.swing.JLabel selectSongLabel;
    private java.util.List songList;
    private javax.persistence.Query songQuery;
    private javax.swing.JScrollPane songScrollPane;
    private javax.swing.JTable songTable;
    // End of variables declaration//GEN-END:variables
}
